package dao;

import domain.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author Freedy
 * @date 2020/12/25 18:04
 */
public interface IRoleDao {

    /**
     * 根据用户id查询出所有对应的角色
     * @param userId
     * @return
     * @throws Exception
     */
    @Select("select * from role where id in (select roleId from users_role where userId=#{userId})")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roleName",column = "roleName"),
            @Result(property = "roleDesc",column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(
                    select = "dao.IPermissionDao.findPermissionByRoleId"
            ))
    })
    List<Role> findRoleByUserId(String userId) throws Exception;

    /**
     * 查询所有
     * @return
     * @throws Exception
     */
    @Select("select * from role")
    List<Role> findAll() throws Exception;

    /**
     * 保存
     * @param role
     * @throws Exception
     */
    @Insert("insert into role(roleName,roleDesc) values(#{roleName},#{roleDesc})")
    void save(Role role) throws Exception;

    /**
     * 根据角色id查询
     * @param id
     * @return
     * @throws Exception
     */
    @Select("select * from role where id=#{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roleName",column = "roleName"),
            @Result(property = "roleDesc",column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(
                    select = "dao.IPermissionDao.findPermissionByRoleId"
            ))
    })
    Role findById(String id) throws Exception;

    /**
     * 根据roleId关联Permission
     * @param permissionId
     * @param roleId
     * @throws Exception
     */
    @Insert("insert into role_permission (permissionId,roleId) values(#{permissionId},#{roleId})")
    void addPermissionByRoleId(@Param("permissionId") int permissionId, @Param("roleId") int roleId) throws Exception;

    /**
     * 根据id删除role
     * @param roleId
     * @throws Exception
     */
    @Delete("delete from role where id=#{roleId}")
    void deleteRole(String roleId) throws Exception;

    /**
     * 根据roleId删除关联表中的数据
     * @param roleId
     * @throws Exception
     */
    @Delete("delete from users_role where roleId=#{roleId}")
    void deleteRoleFromUsersRole(String roleId) throws Exception;

    /**
     * 根据roleId删除关联表中的数据
     * @param roleId
     * @throws Exception
     */
    @Delete("delete from role_permission where roleId=#{roleId}")
    void deleteRoleFromRolePermission(String roleId) throws Exception;
}
